package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.domain.vo.NearUserVo;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.domain.vo.RecommendUserVo;
import com.itheima.domain.vo.VisitorVo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MakeFriendManager {

    @DubboReference
    private RecommendUserService recommendUserService;

    @DubboReference
    private UserInfoService userInfoService;
    //今日佳人
    public ResponseEntity todayBest() {
        //1.获得当前登陆人的id
        Long loginUserId = UserHolder.getUserId();
        //2.查询给当前登录人推荐的用户
        RecommendUser recommendUser = recommendUserService.findTodayBest(loginUserId);

        //此处如果是新用户
        if(recommendUser == null){ //给一个默认推荐的用户
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);//默认推荐1用户
            recommendUser.setScore(RandomUtil.randomDouble(60 , 99 )); //随机数字
            recommendUser.setToUserId( loginUserId );
        }

        //3.recommendUser 只有推荐的id
        UserInfo userInfo = userInfoService.findByUserId(recommendUser.getUserId());
        //4.构建返回值vo
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfo); //赋值userInfo数据 缺少一个缘分值
        vo.setFateValue( recommendUser.getScore().longValue() ); //赋值缘分值
        return ResponseEntity.ok(vo);
    }

    //推荐列表
    public ResponseEntity recommendation(Integer page, Integer pagesize) {
        //1.获得当前登录用户
        Long loginUserId = UserHolder.getUserId();
        //2.查询推荐的列表
        PageBeanVo pageBeanVo = recommendUserService.findRecommedUserByPage(loginUserId, page, pagesize);
        //3.获得List
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();
        List<RecommendUserVo> recommendUserVoList =  new ArrayList<>();

        //添加几条默认的假数据  保证首页有推荐数据 数据相对来说比较真实
        if(CollectionUtil.isEmpty(recommendUserList) ){
            recommendUserList = new ArrayList<>();
            for(int i =1 ; i <= 6 ; i++){
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setToUserId( loginUserId);
                recommendUser.setUserId( Long.valueOf( i ));
                recommendUser.setScore( RandomUtil.randomDouble(66,99));
                recommendUserList.add(recommendUser);
            }
        }

        //4.根据封装的recommendUser对象 查询userInfo
        for (RecommendUser recommendUser : recommendUserList) {
            //4.1 查询用户数据
            UserInfo userInfo = userInfoService.findByUserId(recommendUser.getUserId());
            //5.封装vo
            RecommendUserVo vo = new RecommendUserVo();
            vo.setUserInfo(userInfo);
            //赋值缘分值
            vo.setFateValue( recommendUser.getScore().longValue() ); //赋值缘分值
            recommendUserVoList.add(vo);
        }
        //6.封装pageBeanVo
        pageBeanVo.setItems(recommendUserVoList);
        return ResponseEntity.ok(pageBeanVo);
    }

    //佳人详情
    public ResponseEntity personalInfo(Long jiarenId) {
        //1.获得自己的id
        Long loginUserId = UserHolder.getUserId();
        //2.查询缘分值此处(查询有可能为空)
        RecommendUser recommendUser = recommendUserService.findByJiarenIdAndToUserId(jiarenId, loginUserId);
        if(recommendUser ==null ){//除了解决大数据没有推荐以外  还解决了 我的个人动态 没有缘分值的错误
            recommendUser = new RecommendUser();
            recommendUser.setUserId(jiarenId);//佳人id
            recommendUser.setToUserId(loginUserId);//我的id
            recommendUser.setScore( RandomUtil.randomDouble(66,99) );//随机分数
        }
        //3.查询个人信息
        UserInfo userInfo = userInfoService.findByUserId(jiarenId);
        //4.封装vo
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo( userInfo );
        vo.setFateValue( recommendUser.getScore().longValue() );
        return ResponseEntity.ok(vo);
    }

    @DubboReference
    private VisitorService visitorService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //查看最近访客
    public ResponseEntity findVisitors() {
        //1.获得当前的登陆用户id
        Long userId = UserHolder.getUserId();
        //2.正常逻辑(假定 redis有上次访客时间)  每一个人都有最后一次查看数据的时间  时间暂定2020-10-10
        String lastTime = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);

        /*if(StrUtil.isEmpty(lastTime)){//最后一次时间为空了  没有必要查询了
            //同时必须记录一下 此次操作的时间
            stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME + userId , System.currentTimeMillis()+"");
            return ResponseEntity.ok(null);//返回空数据
        }*/
        //3.查看数据
        List<Visitor> visitorList = visitorService.findVisitorHead4(userId, Long.valueOf(lastTime));
        List<VisitorVo> voList = new ArrayList<>();
        //如果不为空
        if(CollectionUtil.isNotEmpty(visitorList)){
            for (Visitor visitor : visitorList) {
                //4.查询userInfo对象
                UserInfo userInfo = userInfoService.findByUserId(visitor.getVisitorUserId());
                //5.封装vo对象
                VisitorVo vo = new VisitorVo();
                vo.setUserInfo(userInfo);//赋值用户基本数据
                vo.setFateValue(visitor.getScore().longValue());//赋值缘值
                voList.add(vo);
            }
        }
        //更新时间  如果不更新时间问题
        return ResponseEntity.ok(voList);
    }

    @DubboReference
    private UserLocationService userLocationService;
    //上报地理位置
    public ResponseEntity baiduLocation(String latitude, String longitude, String addrStr) {

        //保存位置
        userLocationService.saveOrUpdateLocation(latitude , longitude , addrStr , UserHolder.getUserId());
        return ResponseEntity.ok(null);
    }

    //搜附近
    public ResponseEntity search(String gender, Long distance) {
        //1.获得当前的登录用户id
        Long userId = UserHolder.getUserId();
        //2.查询附近的人
        List<Long> ids = userLocationService.searchNearUser(userId, distance);
        List<NearUserVo> voList = new ArrayList<>(); //构建返回对象
        if(CollectionUtil.isNotEmpty(ids)){
            for (Long id : ids) {
                //搜附近的时候 自己也在圆当中
                if(id == userId){//排除自己
                    continue;
                }
                //3.根据id查询 userInfo信息
                UserInfo userInfo = userInfoService.findByUserId(id);
                if(!StrUtil.equals( gender , userInfo.getGender()  )){//传入的性别不一致  继续循环
                    continue;
                }
                //4.加入集合
                NearUserVo vo = new NearUserVo();
                vo.setUserId( userInfo.getId() );
                vo.setAvatar(  userInfo.getAvatar() );
                vo.setNickname( userInfo.getNickname() );
                voList.add(vo);
            }
        }
        return ResponseEntity.ok( voList );
    }
}
